package cn.com.dashihui.pay.SQ.test;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.rsa.sdk.utils.Base64;

import com.jfinal.kit.PropKit;

import cn.com.dashihui.api.common.PayCode;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.pay.SQ.Kit.ParamUtils;
import net.sf.json.JSONObject;


//查询签约
public class sign_query1 {



	@Test
	public  void test1() throws Exception {
		PropKit.use("config.properties");
		Map<String,String> map = new HashMap<String,String>();
		//开户
//		map.put("phoneNumber", "17746400011");
//		map.put("password", "a5555555");
//		regist(map);
		//登录
		map.put("account", "6874000082");
		map.put("pwd", "333333");
		String s = login(map);
//		map.put("userid", "6874000276");
//		map.put("token", s);
//		queryMoneyOrder(map);
		//修改支付密码
//		map.put("newPwd", "a1111111");
//		map.put("pwd", "a5555555");
//		map.put("token",s);
//		updatePWD(map);
//		Thread.sleep(1000);
//		System.out.print("6666666666666");
//		map.put("account", "6874000276");
//		map.put("pwd", "a1111111");
//		login(map);
		
		//查询余额
//		map.put("token",s);
//		find(map);
		//下单
//		Map<String,String> map1 = new HashMap<String,String>();
//		Map<String,String> map2 = new HashMap<String,String>();
//		map1.put("order_type", "2");//下单类型  1转入  2在线支付  3 转出 
//		String str = "D201905015478965466667";
//		map1.put("order_id", str);
//		map1.put("pay_firmid", "6874000276");
//		map1.put("pay_firmname", "兰雅健");
//		map1.put("pay_phone", "17630502870");
//		map1.put("downmer_code", "6874");//商户编号
//		map1.put("terminal_type", "1");
//		map1.put("terminal_num","MAC");
//		map1.put("order_money","0.01");
//		map1.put("order_fee","0.00");
//		map1.put("order_ip", "127.0.0.1");
//		map1.put("payee_firmname", "江西中艺文创艺术品有限公司");
//		map2.put("ACCT_TYPE", "2");
//		// order_type=3  
//		String json2 = JSONObject.fromObject(map2).toString();
//	
//		map1.put("extend", json2);
//		System.out.println("1111111111"+json2);
//		// order_type=3  
//		
//		map1.put("token",s);
//		createOrder(map1);
//		
//		Thread.sleep(1000);
		//下单详情
		map.put("token",s);
		map.put("order_id", "M201909271124100798372");
		orderDetail(map);
		
		//下单状态
		map.put("token",s);
		map.put("order_id", "M201909271124100798372");
		orderstate(map);
		
//		String token = findImage();
//		findImage(token);
		
//		map.put("phoneNumber", "15537277550");
//		map.put("CAPTCHA", "12321");
//		map.put("CAPTCHA_TOKEN", "32134234");
//		ZYPay.getCode(map);
	}
	//MT1002获取图形验证码    返回userid交互id
	public static String findImage() {
		//请求参数
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", "MT1002");
		String str = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
		return sendPost(str);
	}
	//MT1305出入金查询    返回userid交互id
	public static void findImage(String str1){
		HttpPost httppost= new HttpPost("https://pay.ncwcys.com:8463/midservice/captcha?value="+str1);
		String json = "";
        // 创建参数队列    
		CloseableHttpClient httpclient = null ;
        try {  
        	//使用默认配制创建httpclient实例
//	            CloseableHttpClient httpclient= HttpClients.createDefault();
        	/** 创建httpclient实例，自行设置
        	 * connectionRequestTimeout  从连接处获取数据的超时时间
        	 * setConnectTimeout		  连接上服务器的时间
        	 * socketTimeout			 服务器返回数据的时间
        	 */
            httpclient =HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom()
        			.setConnectionRequestTimeout(2000).setConnectTimeout(2000)
        			.setSocketTimeout(2000).build()).build();
        	// 创建httppost
        	System.out.println("请求网址 " + httppost.getURI());  
        	StringEntity stringEntity = new StringEntity("", ContentType.create("application/x-www-form-urlencoded", "UTF-8"));  
            httppost.setEntity(stringEntity);  
            Scanner scanner = new Scanner(stringEntity.getContent());
            CloseableHttpResponse response = httpclient.execute(httppost); 
            try {
            	  JSONObject js = null;
            	  HttpEntity entity = response.getEntity();
                  if (entity != null) {
                  	  String str = EntityUtils.toString(entity, "UTF-8");
                      System.out.println("--------------------------------------");
                      System.out.println("Response content: " + str);
                      System.out.println("--------------------------------------");
                  }
            } finally {
                response.close();
               
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	 // 关闭连接,释放资源 
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	}
	//MT1305出入金查询    返回userid交互id
	public static void queryMoneyOrder(Map<String,String> dataMap){
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("BEGIN_DATA", "");
		map.put("END_DATA", "");
		map.put("SYSID", "");
		map.put("COMPANY_ID", "");
		map.put("PAGE", "");
		map.put("SIZE", "");
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", PayCode.API.QUERYMONEY_ORDER);
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost("https://pay.ncwcys.com:8463/midservice/api?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
		sendPost2(json,httppost);
	}
	
	//MT1305开户    返回userid交互id
	public static void regist(Map<String,String> dataMap) throws Exception{
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("phoneNumber", ParamUtils.toString(dataMap.get("phoneNumber")));
		map.put("password", ParamUtils.toString(dataMap.get("password")));
		map.put("TJFIRMID", "6874");
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", "MT1305");
		reqMap.put("params", map);
		String str = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
		sendPost(str);
	}
	//MT1100登录  返回token登录凭证
	public static String login(Map<String,String> dataMap){
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("account", ParamUtils.toString(dataMap.get("account")));
		map.put("pwd", ParamUtils.toString(dataMap.get("pwd")));
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", "MT1100");
		reqMap.put("params", map);
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
        return  sendPost(json);
	}
	//MT1103修改支付密码
	public static void updatePWD(Map<String,String> dataMap){
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("pwd", ParamUtils.toString(dataMap.get("pwd")));
		map.put("newPwd", ParamUtils.toString(dataMap.get("newPwd")));
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", "MT1103");
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost("https://pay.ncwcys.com:8463/midservice/api?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
         sendPost2(json,httppost);
	}
	//ST030003下单状态  
	public static void orderstate(Map<String,String> dataMap) throws Exception{
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("sys_code", "1008");
//		map.put("source_type", "B2C");//订单类型
//		map.put("source_id", "B2C");//来源id
		map.put("order_id", ParamUtils.toString(dataMap.get("order_id")));//下单标号
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", "ST030003");
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost("https://pay.ncwcys.com:8463/midservice/api?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
		 sendPost2(json,httppost);
	}
	//ST030004下单详情
	public static void orderDetail(Map<String,String> dataMap) throws Exception{
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("sys_code", "10031");
		map.put("source_type", "B2C");//订单类型
		map.put("source_id", "B2C");//来源id
		map.put("order_id", ParamUtils.toString(dataMap.get("order_id")));//下单标号
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", "ST030004");
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost("https://pay.ncwcys.com:8463/midservice/api?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
         sendPost2(json,httppost);
	}
	//ZB0102余额查询
	public static void find(Map<String,String> dataMap) throws Exception{
		//请求参数
		Map<String,String> map = new HashMap<String,String>();
		map.put("COMPANY_ID", "10100");//子账号
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", "ZB0102");
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost("https://pay.ncwcys.com:8463/midservice/api?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
        // 创建参数队列    
         sendPost2(json,httppost);
	}
	//ST030047下单 
	public static void createOrder(Map<String,String> dataMap) throws Exception {
		//请求参数 
		Map<String,String> map = new HashMap<String,String>();
		map.put("downmer_code", ParamUtils.toString(dataMap.get("downmer_code")));
		map.put("version", "1.0");
		map.put("terminal_type", ParamUtils.toString(dataMap.get("terminal_type")));
		map.put("terminal_num",ParamUtils.toString(dataMap.get("terminal_num")));
		map.put("order_id", ParamUtils.toString(dataMap.get("order_id")));
		map.put("order_detail", "");
		map.put("order_money", ParamUtils.toString(dataMap.get("order_money")));
		map.put("order_time", DatetimeKit.getFormatDate(new Date(),null));
		map.put("order_ip", ParamUtils.toString(dataMap.get("order_ip")));
		map.put("notify_url", "");
		map.put("pay_firmid", ParamUtils.toString(dataMap.get("pay_firmid")));
		map.put("payee_firmid", "6874");
		map.put("is_points",ParamUtils.toString(dataMap.get("is_points")));
		map.put("callback_url", "");
		System.out.println("签名原文"+EncryUtils.createLinkString(map).toString());
//		String sign = EncryUtils.sign(map, "MIICdgIBADANBgkqhkiG9w0BAQEFAASCrxQt/Ef6xRsYEK0xtD+zWhZ+CwSwTw+N9XTNEXnsDze4YY/P/+NDzPkmc/47AJZ9HSM1sUQ==");
		
		String sign = EncryUtils.sign(map, "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANICXbWHyf6JSb0OHeMU3QkYynA8DWZ3cfQIAq5oBGNS3TqDYcypFNIDOzkI2dszc/Fj0zxXGVgptvh2rX60nYLrAd+HseVL1UMpT4cFUedPywmodvyt8UhvIF6DKSiHdXFPbOxJrxQt/vyMnet4545tI+nTFFhLClC0xxTiQOEXAgMBAAECgYAG8n0XHD7aZMBDuMvUT0RgoKlRvSrUUO88G2e7TUWX443d+aqqko1VxTWYVWqfjbwwKBU80cTM3dRns8VZg7ASLT3n7eOtnj6pfKTPYvpmlLoo9nTq2E0UtdjLBTe/n+H9zUlndzWUSFp6HFiWZSamrtZBy1umG9ogGOy3sDdygQJBAPz0EYJiA9x/Ef6xRsYEK0xtD+zWhZ+CwSwTw+N9XTNEXnsDze4YY/P/njxm3F9giUR3KdJQNdfctH8/H1SwNKkCQQDUieNMre5u1M6IVu0kpHVEdd1SE48ARVESOOZuOOt9kMGs1D9ZGobn9aGFvdH27Jbud8ZswhJzJogC5Wg3tD+/AkEAiitvXP7ZCRpH5A1FkWg5lneEWWQcfTLY/ZCWUa7qt9RCn4NGeyXLgz4/WtL80QRUNpe4um6h2pVt6ou6O3I8cQJADybFTXIYzU3ea1nHDhWrRnYgkPlT+HD4lpP32WO1Zf4r0GZRHckGVQLtwNsHXNMA738aZiZvqkXU7F/uTgpLgQJANzYE5srYP0I6g2dCsUbwuOjUzd2hsmcGOe2x0GijFk8l+5ZHEyPrzXeEBHrD3HM/+NDzPkmc/47AJZ9HSM1sUQ==");
		System.out.println("签名："+sign);
		map.put("sign_str",sign);
//		System.out.println("验签原文"+EncryUtils.createLinkString(map).toString());
//		Boolean flag = EncryUtils.checkSign(map,"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSAl21h8n+iUm9Dh3jFN0JGMpwPA1md3H0CAKuaARjUt06g2HMqRTSAzs5CNnbM3PxY9M8VxlYKbb4dq1+tJ2C6wHfh7HlS9VDKU+HBVHnT8sJqHb8rfFIbyBegykoh3VxT2zsSa8ULf78jJ3reOeObSPp0xRYSwpQtMcU4kDhFwIDAQAB+iUm9Dh3jFN0JGMpwPA1md3H0CAKuaARjUt06g2HMqRTSAzs5CNnbM3PxY9M8VxlYKbb4dq1+tJ2C6wHfh7HlS9VDKU+HBVHnT8sJqHb8rfFIbyBegykoh3VxT2zsSa8ULf78jJ3reOeObSPp0xRYSwpQtMcU4kDhFwIDAQAB");
//		System.out.println("验签11111"+flag);
		
		map.put("sys_code", "10031");
		map.put("model_type", "API");
		map.put("trans_scene", "2");
		map.put("source_type", "B2C");
		map.put("source_id", "B2C");
		map.put("order_type", ParamUtils.toString(dataMap.get("order_type")));
		map.put("pay_firmname", ParamUtils.toString(dataMap.get("pay_firmname")));
//		map.put("pay_phone", "");
		map.put("pay_phone", ParamUtils.toString(dataMap.get("pay_phone")));
		map.put("payee_firmname", ParamUtils.toString(dataMap.get("payee_firmname")));
//		map.put("goods_detail", ParamUtils.toString(dataMap.get("goods_detail")));
		map.put("order_fee", ParamUtils.toString(dataMap.get("order_fee")));
//		map.put("order_detail", ParamUtils.toString(dataMap.get("order_detail")));
//		map.put("order_timeout", ParamUtils.toString(dataMap.get("order_timeout")));
//		map.put("subord_detail", ParamUtils.toString(dataMap.get("subord_detail")));
		String json2 = ParamUtils.toString(dataMap.get("extend"));
		json2 = new String(Base64.encodeBase64(json2.getBytes()), "UTF-8");
		json2 = json2.replaceAll("\r", "").replaceAll("\n", "").replace("+", "%2B").replace("=", "%3D");
		map.put("extend", json2);
		

		
		//请求api
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("api", "ST030047");
		reqMap.put("params", map);
		HttpPost httppost= new HttpPost("https://pay.ncwcys.com:8463/midservice/api?TOKEN="+dataMap.get("token"));
		String json = "directives="+"["+JSONObject.fromObject(reqMap).toString()+"]";
		// 创建参数队列    
        sendPost2(json,httppost);		
	}

	public static  String  sendPost( String json) {
		CloseableHttpClient httpclient = null ;
		 String s = null;
        try {  
        	//使用默认配制创建httpclient实例
//            CloseableHttpClient httpclient= HttpClients.createDefault();
        	/** 创建httpclient实例，自行设置
        	 * connectionRequestTimeout  从连接处获取数据的超时时间
        	 * setConnectTimeout		  连接上服务器的时间
        	 * socketTimeout			 服务器返回数据的时间
        	 */
            httpclient =HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom()
        			.setConnectionRequestTimeout(2000).setConnectTimeout(2000)
        			.setSocketTimeout(2000).build()).build();
        	// 创建httppost
            HttpPost httppost= new HttpPost("https://pay.ncwcys.com:8463/midservice/api");
           
        	System.out.println("请求:    "+json);
        	 System.out.println("executing request " + httppost.getURI());  
        	 
        	StringEntity stringEntity = new StringEntity(json, ContentType.create("application/x-www-form-urlencoded", "UTF-8"));  
        	httppost.setEntity(stringEntity);  
            CloseableHttpResponse response = httpclient.execute(httppost); 
            try {
            	JSONObject js = null;
            	  HttpEntity entity = response.getEntity();
                  if (entity != null) {
                  	  String str = EntityUtils.toString(entity, "UTF-8");
                      System.out.println("--------------------------------------");
                      System.out.println("Response content: " + str);
//                      System.out.println("Response content: " + JSONObject.fromObject(str.substring(1, str.length()-1)));
                      System.out.println("--------------------------------------");
                      js =  JSONObject.fromObject(str.substring(1, str.length()-1));
                  }
                  Object ss = js.get("data");
                  js = JSONObject.fromObject(ss);
                  return s = (String)js.get("token");
//                   (String)js.get("CAPTCHA_TOKEN");
//                  return s;
            } finally {
                response.close();
               
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	 // 关闭连接,释放资源 
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		return s;
        
	}
	
	public static  void  sendPost2( String json, HttpPost httppost) {
		CloseableHttpClient httpclient = null ;
		String s = null;
        try {  
        	//使用默认配制创建httpclient实例
//            CloseableHttpClient httpclient= HttpClients.createDefault();
        	/** 创建httpclient实例，自行设置
        	 * connectionRequestTimeout  从连接处获取数据的超时时间
        	 * setConnectTimeout		  连接上服务器的时间
        	 * socketTimeout			 服务器返回数据的时间
        	 */
            httpclient =HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom()
        			.setConnectionRequestTimeout(2000).setConnectTimeout(2000)
        			.setSocketTimeout(2000).build()).build();
        	// 创建httppost
            
        	System.out.println("请求:    "+json);
        	System.out.println("请求网址 " + httppost.getURI());  
        	StringEntity stringEntity = new StringEntity(json, ContentType.create("application/x-www-form-urlencoded", "UTF-8"));  
            httppost.setEntity(stringEntity);  
            Scanner scanner = new Scanner(stringEntity.getContent());
            CloseableHttpResponse response = httpclient.execute(httppost); 
            try {
            	  JSONObject js = null;
            	  HttpEntity entity = response.getEntity();
                  if (entity != null) {
                  	  String str = EntityUtils.toString(entity, "UTF-8");
                      System.out.println("--------------------------------------");
                      System.out.println("Response content: " + str);
//                      System.out.println("Response content: " + JSONObject.fromObject(str.substring(1, str.length()-1)));
                      System.out.println("--------------------------------------");
                      js =  JSONObject.fromObject(str.substring(1, str.length()-1));
                  }
            } finally {
                response.close();
               
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        	 // 关闭连接,释放资源 
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
	}
	
	
	public static  void  sendPost1(List<NameValuePair> formparams,String token) {
		// 创建默认的httpClient实例.
        CloseableHttpClient httpclient =null;
        // 创建httppost
        HttpPost httppost =null;
        UrlEncodedFormEntity uefEntity;  
		StringEntity stringEntity;  
		Map<String,String> map = null;
        try {  
        	httpclient= HttpClients.createDefault();
        	httppost= new HttpPost("https://pay.ncwcys.com:8463/midservice/api?token="+token);
        	System.out.println("请求"+httppost.getURI());
        	System.out.println("请求"+formparams.toString());
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
            System.out.println("请求头"+uefEntity.toString());
            Scanner scanner = new Scanner(uefEntity.getContent());
            System.out.println("请求数据"+scanner.next());
            httppost.setEntity(uefEntity); 
            System.out.println("executing request " + httppost.getURI());  
            CloseableHttpResponse response = httpclient.execute(httppost);  
            try {
            	  HttpEntity entity = response.getEntity();
                  if (entity != null) {
                  	 String str1 = EntityUtils.toString(entity, "UTF-8");
                      System.out.println("--------------------------------------");
                      System.out.println("Response content: " + str1);
                      System.out.println("--------------------------------------");
                  }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源 
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
	}
}
